package com.example.crossborderecommerce.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.crossborderecommerce.entity.*;
import com.example.crossborderecommerce.mapper.SalePromotionMapper;
import com.example.crossborderecommerce.service.*;
import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.ss.usermodel.HorizontalAlignment;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 促销活动模块
 *
 * @author Yolanda
 * @since 2024-05-09
 */
@RestController
@Transactional
@RequestMapping("/sale-promotion")
public class SalePromotionController {
    @Resource
    ISalePromotionService salePromotionService;
    @Resource
    SalePromotionMapper salePromotionMapper;
    @Resource
    IShopService shopService;
    @Resource
    IAdminService adminService;
    @Resource
    IProductService productService;
    @Resource
    IStoreCommodityService storeCommodityService;


    /**
     * 添加促销活动
     * @param salePromotion
     * @return
     */
    @PostMapping("/save")
    public Result save(@RequestBody SalePromotion salePromotion){
        QueryWrapper<StoreCommodity> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("product_id", salePromotion.getStoreCommodityId());
        StoreCommodity storeCommodity = storeCommodityService.getOne(queryWrapper);
        salePromotion.setStoreCommodityId(storeCommodity.getId());
        boolean res = salePromotionService.save(salePromotion);
        if(res){
            return Result.success("添加促销活动成功！");
        }
        return Result.error("添加促销活动失败！");
    }

    /**
     * 删除促销活动
     * @param salePromotion
     * @return
     */
    @PostMapping("/delete")
    public Result delete(@RequestBody SalePromotion salePromotion){
        boolean res = salePromotionService.removeById(salePromotion);
        if(res){
            return Result.success("删除促销活动成功！");
        }
        return Result.error("删除促销活动失败！");
    }

    /**
     * 修改促销活动
     * @param salePromotion
     * @return
     */
    @PostMapping("/update")
    public Result update(@RequestBody SalePromotion salePromotion) {
        boolean res = salePromotionService.saveOrUpdate(salePromotion);
        if (res) {
            return Result.success("修改促销活动成功！");
        }
        return Result.error("修改促销活动失败！");
    }
    
    /**
     * 以列表形式返回所有的促销活动
     * @return
     */
    @GetMapping("/findAll")
    public Result findAll() {
        List<SalePromotion> salePromotionList = salePromotionService.list();
        if(salePromotionList == null) {
            return Result.error("获取全部促销活动信息失败！");
        }
        return Result.success("获取全部促销活动信息成功！", salePromotionList);
    }

    @GetMapping("/findPage")
    public Result findPage(@RequestParam(defaultValue = "") String name,
                           @RequestParam(defaultValue = "") String shopName,
                           @RequestParam(defaultValue = "-1") String adminId,
                           @RequestParam Integer pageNum,
                           @RequestParam Integer pageSize) {
        Page<SalePromotion> salePromotionPage = new Page<>(pageNum, pageSize);
        List<SalePromotion> salePromotionList = salePromotionMapper.getSalePromotionByPage(salePromotionPage, name, shopName, adminId);
        for(SalePromotion salePromotion : salePromotionList) {
           Admin admin = adminService.getById(salePromotion.getAdminId());
           salePromotion.setAdminName(admin.getName());
           if(salePromotion.getShopId() != null) {
               Shop shop = shopService.getById(salePromotion.getShopId());
               salePromotion.setShopName(shop.getName());
           }
           if(salePromotion.getStoreCommodityId() != null) {
               StoreCommodity storeCommodity = storeCommodityService.getById(salePromotion.getStoreCommodityId());
               Product product = productService.getById(storeCommodity.getProductId());
               salePromotion.setStoreCommodityName(product.getName());
           }
        }
        Page<SalePromotion> newSalePromotionPage = new Page<>(pageNum, pageSize);
        newSalePromotionPage.setRecords(salePromotionList);
        newSalePromotionPage.setTotal(salePromotionPage.getTotal());
        return Result.success("成功查询所有促销活动！",newSalePromotionPage);
    }
    /**
     * 导出促销活动
     * @param name
     * @param response
     * @return
     */
    @GetMapping("exportSalePromotionList")
    public Result exportSalepromotionList(@RequestParam(defaultValue = "") String name,
                                         @RequestParam(defaultValue = "") String shopName,
                                         @RequestParam(defaultValue = "-1") String adminId,
                                         HttpServletResponse response) {
        QueryWrapper<SalePromotion> queryWrapper = new QueryWrapper<>();
        List<SalePromotion> salePromotionList = salePromotionService.list(queryWrapper);
        for(SalePromotion salePromotion : salePromotionList) {
            Admin admin = adminService.getById(salePromotion.getAdminId());
            salePromotion.setAdminName(admin.getName());
            if(salePromotion.getShopId() != null) {
                Shop shop = shopService.getById(salePromotion.getShopId());
                salePromotion.setShopName(shop.getName());
            }
            if(salePromotion.getStoreCommodityId() != null) {
                StoreCommodity storeCommodity = storeCommodityService.getById(salePromotion.getStoreCommodityId());
                Product product = productService.getById(storeCommodity.getProductId());
                salePromotion.setStoreCommodityName(product.getName());
            }
        }
        HSSFWorkbook wb = new HSSFWorkbook(); // 导出到excel文件中
        HSSFSheet sheet = wb.createSheet("表一");
        HSSFRow row = sheet.createRow(0);
        HSSFCellStyle style = wb.createCellStyle();
        style.setAlignment(HorizontalAlignment.CENTER);
        HSSFCell cell = row.createCell((short) 0);
        cell.setCellValue("ID");
        cell.setCellStyle(style);
        cell = row.createCell((short) 1);
        cell.setCellValue("活动名称");
        cell.setCellStyle(style);
        cell = row.createCell((short) 2);
        cell.setCellValue("开始时间");
        cell.setCellStyle(style);
        cell = row.createCell((short) 3);
        cell.setCellValue("截止时间");
        cell.setCellStyle(style);
        cell = row.createCell((short)4);
        cell.setCellValue("规则");
        cell.setCellStyle(style);
        cell = row.createCell((short)5);
        cell.setCellValue("店铺名称");
        cell.setCellStyle(style);
        cell = row.createCell((short)6);
        cell.setCellValue("指定货物");
        cell.setCellStyle(style);
        cell = row.createCell((short)7);
        cell.setCellValue("折扣力度");
        cell.setCellStyle(style);
        cell = row.createCell((short)8);
        cell.setCellValue("创建人");
        cell.setCellStyle(style);
        cell = row.createCell((short)9);
        cell.setCellValue("创建时间");
        cell.setCellStyle(style);
        SimpleDateFormat inputDateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
        SimpleDateFormat outputDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        for (int i = 0; i < salePromotionList.size(); i++) {
            row = sheet.createRow(i + 1);
            SalePromotion salePromotion = salePromotionList.get(i);
            row.createCell((short) 0).setCellValue(salePromotion.getId());
            row.createCell((short) 1).setCellValue(salePromotion.getName());
            row.createCell((short) 4).setCellValue(salePromotion.getRule());
            row.createCell((short) 5).setCellValue(salePromotion.getShopName());
            row.createCell((short) 6).setCellValue(salePromotion.getStoreCommodityName());
            row.createCell((short) 7).setCellValue(salePromotion.getPromotionRate());
            row.createCell((short) 8).setCellValue(salePromotion.getAdminName());
            try {
                Date startTime =inputDateFormat.parse(salePromotion.getStartTime().toString());
                Date endTime=inputDateFormat.parse(salePromotion.getEndTime().toString());
                Date createTime = inputDateFormat.parse(salePromotion.getCreateTime().toString()); // 假设 getCreateTime 返回的是 String
                row.createCell((short) 9).setCellValue(outputDateFormat.format(createTime));
                row.createCell((short) 2).setCellValue(outputDateFormat.format(startTime));
                row.createCell((short) 3).setCellValue(outputDateFormat.format(endTime));
            } catch (ParseException e) {
                row.createCell((short) 9).setCellValue(salePromotion.getCreateTime().toString());
                row.createCell((short) 2).setCellValue(salePromotion.getStartTime().toString());
                row.createCell((short) 3).setCellValue(salePromotion.getEndTime().toString());
            }
        }
        String fileName = "exportSalePromotionList.xls";
        // 用户下载
        try {
            ServletOutputStream outputStream = null;
            response.setHeader("Access-Control-Expose-Headers", "Content-Disposition");
            response.setHeader("Content-Disposition", "attachment;filename="+ URLEncoder.encode(fileName, "UTF-8"));
            outputStream = response.getOutputStream();
            wb.write(outputStream);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        return Result.success("exportSalePromotionList");
    }
    /**
     * 删除一系列促销活动
     * @param ids
     * @return
     */
    @GetMapping("/deleteBatch")
    public Result deleteBatch(@RequestParam String ids) {
        List<String> salePromotionIds = Arrays.stream(ids.split(",")).collect(Collectors.toList());
        boolean res = salePromotionService.removeByIds(salePromotionIds);
        if(res) {
            return Result.success("删除促销活动成功");
        }
        return Result.error("删除促销活动失败！");
    }
}
